package com.fivefox.common.authentication;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fivefox.common.FeiShuHTTPResult;
import com.fivefox.common.configuration.FeiShuAppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 飞书访问凭证接口实现类
 *
 * @author lirenqi
 */
@Component
public class AccessCredentialsTool {

    /**
     * 自建应用获取 app_access_token 的URL
     */
    public final static String APP_ACCESS_TOKEN_URL = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";

   static Logger logger = LoggerFactory.getLogger(AccessCredentialsTool.class);

    @Resource
    private FeiShuAppConfig feiShuAppConfig;

    /**
     * 自建应用获取 app_access_token
     */
    public String getAppAccessToken() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("app_id", feiShuAppConfig.getId());
        paramMap.put("app_secret", feiShuAppConfig.getSecret());
        String result = HttpUtil.post(APP_ACCESS_TOKEN_URL, paramMap);
        FeiShuHTTPResult body = JSONObject.parseObject(result, FeiShuHTTPResult.class);
        if (body.getCode() != 0) {
            logger.error("获取接口token时出现异常：" + body.getMsg());
            return null;
        }
        return body.getTenant_access_token();
    }

    public String refreshAccessToken() {
        return null;
    }

}
